use super::arg_parser::Config;
use std::error::Error;
use std::fs;

/// search query in file contents  
/// # Arguments
/// 1. query: query string
/// 2. contents: file contents
/// 3. return: Vec<&'a str>

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents.lines().filter(|line| line.contains(query)).collect()
}

/// case insensitive search  
/// # Arguments
/// 1. query: query string
/// 2. contents: file contents
/// 3. return: Vec<&'a str>
pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let query = query.to_lowercase();
    contents.lines().filter(|line| line.to_lowercase().contains(&query)).collect()
}

/// the application real entry point
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    if let Some(filepath) = config.filepath {
        println!("filepath: {}", filepath);

        let contents = fs::read_to_string(filepath)?;
        
        let rlt = if config.case_insensitive {search_case_insensitive(&config.query, &contents)} else {search(&config.query, &contents)};
        println!("search result: {:?}", rlt);
        Ok(())
    }else {
        Err("no filepath".into())
    }
}